package ru.aptu.socket_factory;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.File;
import java.io.IOException;
import java.net.Socket;

/**
 * Created by IntelliJ IDEA.
 * User: andrey
 * Date: 2/10/12
 * Time: 3:27 PM
 */

public class BillingSocketFactory {

    public static class SSLSocketCreationException extends Exception {
    }

    public static Socket createSocket(int port, String host) throws IOException {

        String certificate = System.getProperty("javax.net.ssl.trustStore");
        String password = System.getProperty("javax.net.ssl.trustStorePassword");

        try {
            if (certificate == null || certificate.equals("") || password == null || password.equals("") || !(new File(certificate)).isFile()) {
                throw new SSLSocketCreationException();
            } else {
                SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
                try {
                    return sslSocketFactory.createSocket(host, port);
                } catch (IOException e) {
                    throw new SSLSocketCreationException();
                }
            }
        } catch (SSLSocketCreationException ex) {
            SocketFactory socketFactory = SocketFactory.getDefault();
            return socketFactory.createSocket(host, port);
        }
    }
}
